package cn.net.shuxing.yifu.common.back.controller;

import cn.net.shuxing.yifu.common.bean.*;
import cn.net.shuxing.yifu.common.constant.UserState;
import cn.net.shuxing.yifu.common.constant.UserType;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.dto.CodeConst;
import cn.net.shuxing.yifu.common.dto.DataDto;
import cn.net.shuxing.yifu.common.service.*;
import cn.net.shuxing.yifu.common.util.MD5Util;
import cn.net.shuxing.yifu.mysiteforme.admin.service.UploadService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import cn.net.shuxing.yifu.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/back/admin")
public class AdminController {

    @Autowired
    private ShareholderLevelListService shareholderLevelListServive;

    @Autowired
    private MemberLevelService memberLevelService;

    @Autowired
    private LevelGrantService levelGrantService;

    @Autowired
    private UserTransferService userTransferService;

    @Autowired
    private UserCommonService userCommonService;

    @Autowired
    private DealParamService dealParamService;

    @Autowired
    private ShareholderService shareholderService;

    @Autowired
    private ShareholderCommonService shareholderCommonService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShareholderLevelService shareholderLevelService;

    @Autowired
    private UserCapitalService userCapitalService;

    @Autowired
    private UserBankCardService userBankCardService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserInfoBindService userInfoBindService;

    @Autowired
    private UserRealInfoService userRealInfoService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserWalletFrozeService userWalletFrozeService;

    @Autowired
    @Qualifier("ossService")
    private UploadService ossService;

    //    @ResponseBody
    @RequestMapping("/shareholder/add")
    public BaseDto registShareholder(
            HttpServletResponse response,
            String userRealName,
            String phoneNum,
            Integer cardTypeId,
            String idCardNum,
            String openBank,
            String openBankBranch,
            String bankCardNum,
            BigDecimal sleepCoinCount,
            Integer shareholderLevel,
            String password,
            Integer coinTypeId) {
        String name = userRealName;
        BaseDto baseDto = shareholderService.registShareholder(name, phoneNum,
                cardTypeId, idCardNum,
                openBank, openBankBranch,
                bankCardNum, sleepCoinCount,
                shareholderLevel, password, coinTypeId);
        return baseDto;
    }


    @RequestMapping("/shareholder/list")
    public BaseDto shareholderList(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                                   @RequestParam(defaultValue = "15", value = "pageSize") int pageSize) {
        BaseDto baseDto = new BaseDto();
        List<Integer> userIds = userRoleService.getsByUserRole(UserType.SHAREHOLDER);
        Page page = null;
        ArrayList<Object> list = new ArrayList<>();
        if (userIds == null || userIds.isEmpty()) {
            baseDto.setMsg("无股东数据,请添加股东");
            baseDto.setCode(CodeConst.ERROR);
        } else {
            page = PageHelper.startPage(pageNum, pageSize);
            for (Integer userId : userIds) {
                ShareholderCompletedInfo shareholderCompletedInfo = shareholderCommonService.searchByUserId(userId);
                list.add(shareholderCompletedInfo);
            }
            PageInfo<Object> pageInfo = new PageInfo<>(list);
            pageInfo.setTotal(page.getTotal());
            baseDto.setData(pageInfo);
        }
        return baseDto;
    }

//    @RequestMapping("/shareholder/newList")
//    public DataDto newShareholderList(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
//                                      @RequestParam(defaultValue = "15", value = "pageSize") int pageSize) {
//        DataDto baseDto = new DataDto();
//        List<Integer> userIds = userRoleService.getsByUserRole(UserType.SHAREHOLDER);
////        List<User> userList = userService.getsByList(userIds);
//        ArrayList<Object> list = new ArrayList<>();
//        if (userIds == null || userIds.isEmpty()) {
//            baseDto.setMsg("无股东数据,请添加股东");
//            baseDto.setCode(CodeConst.ERROR);
//            baseDto.setCount(0);
//        } else {
//            Page page = PageHelper.startPage(pageNum, pageSize);
//            for (Integer userId : userIds) {
//                ShareholderCompletedInfo shareholderCompletedInfo = shareholderCommonService.searchByUserId(userId);
//                list.add(shareholderCompletedInfo);
//            }
//            PageInfo<Object> pageInfo = new PageInfo<>(list);
//            pageInfo.setTotal(page.getTotal());
//            baseDto.setData(pageInfo);
//            baseDto.setCount(list.size());
//        }
//        return baseDto;
//    }

    @RequestMapping("/member/list")
    public BaseDto memberList(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                              @RequestParam(defaultValue = "15", value = "pageSize") int pageSize) {
        BaseDto baseDto = new BaseDto();
        List<Integer> member = userRoleService.getsByUserRole(UserType.MEMBER);
        List<Integer> none = userRoleService.getsByUserRole(UserType.NONE);
        ArrayList<Object> list = new ArrayList<>();
        Page page = PageHelper.startPage(pageNum, pageSize);
        if (member == null || member.isEmpty()) {
        } else {
            for (Integer id : member) {
                UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(id);
                User user = userCompletedInfo.getUser();
                user.setUserTypeName("会员");
                list.add(userCompletedInfo);
            }
        }

        if (none == null || none.isEmpty()) {
        } else {
            for (Integer id : none) {
                UserCompletedInfo userCompletedInfo = userCommonService.searchByUserId(id);
                User user = userCompletedInfo.getUser();
                user.setUserTypeName("会员(未激活)");
                list.add(userCompletedInfo);
            }
        }

        PageInfo<Object> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(page.getTotal());
        baseDto.setData(pageInfo);

        return baseDto;
    }

    @RequestMapping("/getobjecturl")
    public BaseDto getObjectUrl(String url) {
        if (Strings.isNullOrEmpty(url)) {
            return null;
        }
        return BaseDto.ok(ossService.getUrl(url));
    }

    /**
     * 通过姓名,手机号,身份证号查找股东信息
     *
     * @param userName
     * @param phoneNum
     * @param idCardNum
     * @return
     */
//    @GetMapping(value = "/member/search",produces = {"text/plain;charset=GB2312"})
    @RequestMapping("/member/search")
    public BaseDto memberEdit(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                              @RequestParam(defaultValue = "15", value = "pageSize") int pageSize,
                              String userName, String phoneNum, String idCardNum) throws UnsupportedEncodingException {
        List<UserCompletedInfo> userCompletedInfos = userCommonService.searchMByNameAndPhoneNumAndIdCardNum(userName, phoneNum, idCardNum,pageNum,pageSize);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userCompletedInfos);
        return baseDto;
    }

    /**
     * 通过姓名,手机号,身份证号查找股东信息
     *
     * @param userName
     * @param phoneNum
     * @param idCardNum
     * @return
     */
    @RequestMapping("/shareholder/search")
    public BaseDto shareholderEdit(@RequestParam(defaultValue = "1", value = "page") int pageNum,
                                   @RequestParam(defaultValue = "15", value = "limit") int pageSize,
                                   String userName, String phoneNum, String idCardNum) {
        BaseDto baseDto = new BaseDto();
        if (userName == null && phoneNum == null && idCardNum == null) {
            baseDto = shareholderList(pageNum, pageSize);
        } else {
            List<ShareholderCompletedInfo> ShareholderCompletedInfos = shareholderCommonService.searchSByNameAndPhoneNumAndIdCardNum(userName, phoneNum, idCardNum);
            Page page = PageHelper.startPage(pageNum, pageSize);
            PageInfo<ShareholderCompletedInfo> pageInfo = new PageInfo<>(ShareholderCompletedInfos);
            pageInfo.setTotal(page.getTotal());
            baseDto.setData(pageInfo);
        }

        return baseDto;
    }

//    @RequestMapping("/shareholder/newSearch")
//    public DataDto newShareholderEdit(@RequestParam(defaultValue = "1", value = "page") int pageNum,
//                                      @RequestParam(defaultValue = "15", value = "limit") int pageSize,
//                                      String userName, String phoneNum, String idCardNum) {
////        DataDto dataDto = new DataDto();
////        if (userName==null && phoneNum==null && idCardNum==null){
////            dataDto = shareholderList(pageNum, pageSize);
////        }else {
////            List<ShareholderCompletedInfo> ShareholderCompletedInfos = shareholderCommonService.searchSByNameAndPhoneNumAndIdCardNum(userName, phoneNum, idCardNum);
////            Page page = PageHelper.startPage(pageNum,pageSize)
////            dataDto.setData(new PageInfo<ShareholderCompletedInfo>(ShareholderCompletedInfos));
////        }
////
////        return dataDto;
//        DataDto dataDto = new DataDto();
//        if (userName == null && phoneNum == null && idCardNum == null) {
//            dataDto = newShareholderList(pageNum, pageSize);
//        } else {
//            List<ShareholderCompletedInfo> ShareholderCompletedInfos = shareholderCommonService.searchSByNameAndPhoneNumAndIdCardNum(userName, phoneNum, idCardNum);
//            Page page = PageHelper.startPage(pageNum, pageSize);
//            PageInfo<ShareholderCompletedInfo> pageInfo = new PageInfo<>(ShareholderCompletedInfos);
//            pageInfo.setTotal(page.getTotal());
//            dataDto.setData(pageInfo);
//            dataDto.setCount(ShareholderCompletedInfos.size());
//        }
//
//        return dataDto;
//    }


    //   2-2.筛选：可通过股东等级、注册时间区间、休眠币数量区间、活币数量区间、股东状态进行股东筛选
    @RequestMapping("/shareholder/sift")
    public BaseDto shareholderSift(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                                   @RequestParam(defaultValue = "15", value = "pageSize") int pageSize,
                                   Integer lowLevel,
                                   Integer highLevel,
                                   String startRegisterTime,
                                   String endRegisterTime,
                                   BigDecimal maxSleepCoinCount,
                                   BigDecimal minSleepCoinCount,
                                   BigDecimal maxAliveCoinCount,
                                   BigDecimal minAliveCoinCount,
                                   Integer shareholderState,
                                   @RequestParam(defaultValue = "1", value = "coinTypeId") int coinTypeId) {
        LocalDateTime startRegisterTimeObj = null;
        LocalDateTime endRegisterTimeObj = null;
        if (StringUtils.hasText(startRegisterTime)) {
            startRegisterTimeObj = LocalDateTime.parse(startRegisterTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        if (StringUtils.hasText(endRegisterTime)) {
            endRegisterTimeObj = LocalDateTime.parse(endRegisterTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }

        BaseDto search = shareholderCommonService.search(pageNum, pageSize, null, null, null,
                coinTypeId, lowLevel, highLevel,
                startRegisterTimeObj, endRegisterTimeObj,
                minSleepCoinCount, maxSleepCoinCount,
                minAliveCoinCount, maxAliveCoinCount, shareholderState);
        return search;
    }

//       2-1.搜索：可通过姓名、手机号、身份证号进行会员搜索
//   2-2.筛选：可通过注册时间区间、活币数量区间、交易完成量区间、所在城市进行筛选

    @RequestMapping("/member/sift")
    public BaseDto memberSift(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                              @RequestParam(defaultValue = "15", value = "pageSize") int pageSize,
                              String startRegisterTime,
                              String endRegisterTime,
                              BigDecimal minDealedCount,
                              BigDecimal maxDealedCount,
                              BigDecimal minAliveCoinCount,
                              BigDecimal maxAliveCoinCount,
                              Integer memberState,
                              @RequestParam(defaultValue = "1", value = "coinTypeId") int coinTypeId) {
        LocalDateTime startRegisterTimeObj = null;
        LocalDateTime endRegisterTimeObj = null;
        if (StringUtils.hasText(startRegisterTime)) {
            startRegisterTimeObj = LocalDateTime.parse(startRegisterTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        if (StringUtils.hasText(endRegisterTime)) {
            endRegisterTimeObj = LocalDateTime.parse(endRegisterTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        BaseDto search = userCommonService.search(pageNum, pageSize, null, null, null,
                coinTypeId, startRegisterTimeObj, endRegisterTimeObj, minDealedCount, maxDealedCount,
                minAliveCoinCount, maxAliveCoinCount, memberState);
        return search;
    }

    /**
     * 封号
     *
     * @param userId
     */
    @RequestMapping("/admin/close")
    public void shareholderClosed(HttpServletResponse response , Integer userId) throws IOException {
        User user = userService.getByPrimaryKey(userId);
        user.setState(UserState.CLOSED);
        user.setUpdateTime(LocalDateTime.now());
        userService.update(user);
        response.sendRedirect("/back/admin/shareholder/searchPage");
    }

    /**
     * 解封
     *
     * @param userId
     */
    @RequestMapping("/admin/unclose")
    public Integer shareholderUnclose(Integer userId) {
        User user = userService.getByPrimaryKey(userId);
        user.setState(UserState.OK);
        user.setUpdateTime(LocalDateTime.now());
        userService.update(user);
        return CodeConst.OK;
    }

    /**
     * 冻结
     *
     * @param userId
     */
    @RequestMapping("/admin/frozen")
    public Integer adminFrozen(Integer userId, Integer userType) {
        User user = userService.getByPrimaryKeyWithoutComplete(userId);
        if (user == null)
            return CodeConst.ERROR;
        boolean flag = userService.hasRole(userId, userType);
        if (!flag)
            return CodeConst.ERROR;
        userWalletFrozeService.frozeUser(userId, userType);
        return CodeConst.OK;
    }



    /**
     * @param userId   用户id
     * @param userType 用户身份(钱包类型)
     * @return
     */
    @RequestMapping("/admin/active")
    public Integer adminActive(Integer userId, Integer userType) {
        User user = userService.getByPrimaryKeyWithoutComplete(userId);
        if (user == null)
            return CodeConst.ERROR;
        boolean flag = userService.hasRole(userId, userType);
        if (!flag)
            return CodeConst.ERROR;
        UserRole userRole = userRoleService.getByUserIdAndUserRole(userId, userType);
        userRole.setLastExamTime(LocalDateTime.now());
        userRole.setState(UserState.OK);
        userRoleService.update(userRole);
        if (user.getType() == userType) {
            userService.updateState(userId, UserState.OK);
        }
        return CodeConst.OK;
    }

    /**
     * 单个股东用户详情
     *
     * @param userId
     * @return
     */
    @RequestMapping("/admin/userDetail")
    public BaseDto shareholderUserDetail(Integer userId) {
        BaseDto baseDto = new BaseDto();
        User user = userService.getByPrimaryKey(userId);
        UserRealInfo userRealInfo = userRealInfoService.getByPrimaryKey(userId);
        Map map = new HashMap<>();
        map.put("User", user);
        map.put("UserRealInfo", userRealInfo);
        baseDto.setData(map);
        return baseDto;
    }

    /**
     * 单个股东""
     *
     * @param userId
     * @return
     */
    @RequestMapping("/admin/bankDetail")
    public BaseDto shareholderBankDetail(Integer userId) {
        BaseDto baseDto = new BaseDto();
        List<UserBankCard> userBankCardList = userBankCardService.getsByUserId(userId);
        baseDto.setData(userBankCardList);
        return baseDto;
    }

    /**
     * 单个股东资产详情
     *
     * @param userId
     * @return
     */
    @RequestMapping("/admin/capitalDetail")
    public BaseDto shareholderCapitalDetail(Integer userId, Integer userType, @RequestParam(defaultValue = "1", value = "coinTypeId") int coinTypeId) {
        BaseDto baseDto = new BaseDto();
        UserCapital userCapitals = userCapitalService.getsCapitalByUserIdAndUserRole(userId, userType, coinTypeId);
        baseDto.setData(userCapitals);
        return baseDto;
    }

    // 股东姓名、
// 手机号、
// 身份证号、
// 股东等级、
// 登录密码
//--------------
    @RequestMapping("/shareholder/updateInfo")
    public BaseDto shareholderUpdateInfo(Integer userId,
                                         String newPassword,
                                         Integer level,
                                         String idCardNum,
                                         String phoneNum,
                                         String nickName
    ) {
        BaseDto baseDto = new BaseDto();
        //获取登录密码
        User user = userService.getByPrimaryKey(userId);
        String password = user.getPassword();
        if (password.equals(newPassword)) {
            baseDto.setMsg("新密码不能与旧密码相同");
        }
        user.setPassword(newPassword);
        userService.update(user);
        //获取股东等级
        ShareholderLevel shareholderLevel = shareholderLevelService.getByShareholderId(userId);
        shareholderLevel.setLevel(level);
        shareholderLevelService.update(shareholderLevel);
        //身份证号
        UserRealInfo userRealInfo = userRealInfoService.getByPrimaryKey(userId);
        userRealInfo.setIdCardNum(idCardNum);
        userRealInfoService.update(userRealInfo);
        //手机号
        UserInfoBind userInfoBind = userInfoBindService.getByPrimaryKey(userId);
        userInfoBind.setSPhoneNum(phoneNum);
        userInfoBindService.update(userInfoBind);
        //股东姓名
        UserInfo userInfo = userInfoService.getByPrimaryKey(userId);
        userInfo.setNickName(nickName);
        userInfoService.update(userInfo);
        baseDto = this.shareholderUserDetail(userId);
        return baseDto;
    }

    /**
     * 修改银行卡信息
     *
     * @param id             银行卡记录主键id
     * @param bankCardNum    卡号
     * @param openBank       开户银行
     * @param openBankBranch 开户支行
     * @param phoneNum       银行预留手机号
     * @return
     */
    @RequestMapping("/admin/updateBankInfo")
    public BaseDto adminUpdateBankInfo(Integer id,
                                       String bankCardNum,
                                       String openBank,
                                       String openBankBranch,
                                       String phoneNum) {
        UserBankCard userBankCard = userBankCardService.getByPrimaryKey(id);
        userBankCard.setBankCardNum(bankCardNum);
        userBankCard.setOpenBank(openBank);
        userBankCard.setOpenBankBranch(openBankBranch);
        userBankCard.setPhoneNum(phoneNum);
        userBankCardService.update(userBankCard);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userBankCardService.getByPrimaryKey(id));
        return baseDto;
    }

    /**
     * 用户银行卡信息列表
     *
     * @param userId
     * @return
     */
    @RequestMapping("/admin/bankInfoList")
    public BaseDto adminUpdateBankInfoList(Integer userId) {
        List<UserBankCard> userBankCardList = userBankCardService.getsByUserId(userId);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userBankCardList);
        return baseDto;
    }

    @RequestMapping("/admin/bankInfo")
    public BaseDto adminUpdateBankInfo(Integer id) {
        UserBankCard userBankCard = userBankCardService.getByPrimaryKey(id);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userBankCard);
        return baseDto;
    }


    @RequestMapping("/admin/userBankInfo")
    public BaseDto adminUserBankInfo(Integer userId) {
        List<UserBankCard> userBankCards = userBankCardService.getsByUserId(userId);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userBankCards);
        return baseDto;
    }

    /**
     * 删除绑定银行卡
     *
     * @param response
     * @param id
     * @throws IOException
     */
    @RequestMapping("/admin/delBankinfo")
    public void adminDelBankInfo(HttpServletResponse response, Integer id) throws IOException {
        userBankCardService.delete(id);
        response.sendRedirect("bankInfoListPage");
    }

    /**
     * 修改银行卡信息
     *
     * @param id             银行卡信息表主键
     * @param bankCardNum
     * @param openBank
     * @param openBankBranch
     * @param phoneNum
     * @throws IOException
     */
    @RequestMapping("/admin/bankInfoUpdate")
    public Integer adminBankInfoUpdate(Integer id,
                                       String bankCardNum,
                                       String openBank,
                                       String openBankBranch,
                                       String phoneNum) throws IOException {
        UserBankCard userBankCard = userBankCardService.getByPrimaryKey(id);
        userBankCard.setPhoneNum(phoneNum);
        userBankCard.setBankCardNum(bankCardNum);
        userBankCard.setOpenBank(openBank);
        userBankCard.setOpenBankBranch(openBankBranch);
        boolean b = userBankCardService.updateUserBankCard(userBankCard);
        return userBankCard.getUserId();
    }


    @RequestMapping("/admin/userInfoUpdate")
    public String adminUserInfoUpdate(Integer userId,
                                      String password) {
        User user = userService.getByPrimaryKey(userId);
        user.setPassword(MD5Util.md5(password));
        userService.update(user);
        return "成功";
    }


    /**
     * 用户资产列表
     *
     * @param userId
     * @return
     */
    @RequestMapping("/admin/capitalList")
    public BaseDto adminCapitalList(Integer userId) {
        List<UserCapital> userCapitals = userCapitalService.getsByUserId(userId);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userCapitals);
        return baseDto;
    }

    /**
     * 修改用户活币与休眠币数量
     *
     * @param id
     * @param userId
     * @param aliveCoinCount
     * @param sleepCoinCount
     * @throws IOException
     */
    @RequestMapping("/admin/capital")
    public String adminCapital(HttpServletResponse response,
                               Integer id,
                               Integer userId,
                               BigDecimal aliveCoinCount,
                               BigDecimal sleepCoinCount,
                               Integer userType) throws IOException {
        UserCapital userCapital = userCapitalService.getByPrimaryKey(id);
        userCapital.setAliveCoinCount(aliveCoinCount);
        userCapital.setSleepCoinCount(sleepCoinCount);
        userCapitalService.update(userCapital);
//        response.sendRedirect("userCapitalPage?userId=" + userId + "&userType=" + userType);
        return "成功";
    }

    /**
     * 获取该股东的交易参数
     *
     * @param userId
     * @return
     */
    @RequestMapping("/admin/paramList")
    public BaseDto shareholderParamList(Integer userId) {
        List<DealParam> dealParams = dealParamService.getsByUserId(userId);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(dealParams);
        return baseDto;
    }

    /**
     * 修改用户对应交易参数
     *
     * @param response
     * @param dealParamId
     * @param dealParamKey
     * @param dealParamValue
     * @return
     */
    @RequestMapping("/admin/param")
    public void shareholderParamList(HttpServletResponse response,
                                     Integer dealParamId,
                                     Integer dealParamKey,
                                     String dealParamValue) throws IOException {
        DealParam dealParam = dealParamService.getByPrimaryKey(dealParamId);
        dealParam.setDealParamKey(dealParamKey);
        dealParam.setDealParamValue(dealParamValue);
        dealParamService.update(dealParam);
        response.sendRedirect("adminParamListPage");
    }

    @RequestMapping("/member/transfer")
    public BaseDto memberTransfer(Integer memberId) {
        List<UserTransfer> userTransfers = userTransferService.getsTransferByUserType(memberId, UserType.MEMBER);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(userTransfers);
        return baseDto;
    }


    /**
     * 获取所有股东等级信息
     *
     * @param coinTypeId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/level/list")
    public BaseDto levelList(Integer coinTypeId,
                             @RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                             @RequestParam(defaultValue = "15", value = "pageSize") int pageSize) {
        BaseDto baseDto = new BaseDto();
        List<LevelGrant> levelList = levelGrantService.getsByCoinTypeId(coinTypeId);
        Page page = PageHelper.startPage(pageNum, pageSize);
        PageInfo<LevelGrant> pageInfo = new PageInfo<>(levelList);
        pageInfo.setTotal(page.getTotal());
        baseDto.setData(pageInfo);
        return baseDto;
    }

    /**
     * 修改股东等级名称及对应的活币和休眠币配发量
     *
     * @param id
     * @param aliveCoinCount
     * @param sleepCoinCount
     * @param name
     * @return
     */
    @RequestMapping("/level/update")
    public BaseDto levelUpdate(HttpServletResponse response,
                               Integer id,
                               BigDecimal aliveCoinCount,
                               BigDecimal sleepCoinCount,
                               String name) throws IOException {
        BaseDto baseDto = new BaseDto();
        LevelGrant levelGrant = levelGrantService.getByPrimaryKey(id);
        levelGrant.setAliveCoinCount(aliveCoinCount);
        levelGrant.setSleepCoinCount(sleepCoinCount);
        levelGrant.setName(name);
        boolean b = levelGrantService.checkLevelAndName(levelGrant.getCoinTypeId(), levelGrant.getLevel(), name);
        if (b) {
            levelGrantService.update(levelGrant);
            baseDto.setData(CodeConst.OK);
        } else {
            baseDto.setData(CodeConst.ERROR);
            baseDto.setMsg("修改失败,名称相同");
            response.sendRedirect("/back/admin/level/listpage");
        }
        return baseDto;
    }


    @RequestMapping("/level/del")
    public BaseDto levelDel(Integer id) {
        BaseDto baseDto = new BaseDto();
        boolean delete = levelGrantService.delete(id);
        if (delete) {
            baseDto.setData("成功");
        } else {
            baseDto.setData("失败");
            baseDto.setCode(CodeConst.ERROR);
        }
        return baseDto;
    }


    @RequestMapping("/level/add")
    public BaseDto levelAdd(String name,
                            Integer level,
                            Integer coinTypeId,
                            BigDecimal aliveCoinCount,
                            BigDecimal sleepCoinCount) {
        BaseDto baseDto = new BaseDto();
        boolean b = levelGrantService.checkLevelAndName(coinTypeId, level, name);
        if (b) {
            levelGrantService.insert(name, level, coinTypeId, aliveCoinCount, sleepCoinCount);
            baseDto.setCode(CodeConst.OK);
        } else {
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("等级或名称重复,添加失败");
        }
        return baseDto;
    }

    @RequestMapping("/shareholder/userDetail")
    public BaseDto shareholderUserDetail(Integer userId,
                                         @RequestParam(defaultValue = "1", value = "coinTypeId") int coinTypeId) {
        BaseDto baseDto = new BaseDto();
        ShareholderDetail shareholderDetail = shareholderCommonService.shareholderUserDetail(userId, coinTypeId, UserType.SHAREHOLDER);
        baseDto.setData(shareholderDetail);
        return baseDto;
    }

    @RequestMapping("/member/userDetail")
    public BaseDto memberUserDetail(Integer userId,
                                    @RequestParam(defaultValue = "1", value = "coinTypeId") int coinTypeId) {
        BaseDto baseDto = new BaseDto();
        ShareholderDetail memberDetail = userCommonService.memberShareholderDetail(userId, coinTypeId);
        baseDto.setData(memberDetail);
        return baseDto;
    }

    @RequestMapping("/member/updateUser")
    public BaseDto memberUpdateUser(Integer userId,
                                    Integer coinTypeId,
                                    BigDecimal aliveCoinCount,
                                    BigDecimal sleepCoinCount,
                                    String password) {
        BaseDto baseDto = new BaseDto();
        try {
            UserCapital userCapital = userCapitalService.getByUserIdAndCoinTypeIdAndUserType(userId, coinTypeId, UserType.MEMBER);
            if (userCapital != null) {
                userCapital.setAliveCoinCount(aliveCoinCount);
                userCapital.setSleepCoinCount(sleepCoinCount);
                userCapitalService.update(userCapital);
            }
            if (password != null) {
                User user = userService.getByPrimaryKey(userId);
                user.setPassword(MD5Util.md5(password));
                userService.update(user);
            }
            baseDto.setData("修改成功");
        } catch (Exception e) {
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("修改失败");
        }
        return baseDto;
    }

    @RequestMapping("/shareholder/updateUser")
    public BaseDto shareholderUpdateUser(Integer userId,
                                         Integer coinTypeId,
                                         BigDecimal aliveCoinCount,
                                         BigDecimal sleepCoinCount,
                                         String password,
                                         Integer shareholderLevel) {
        BaseDto baseDto = new BaseDto();
        try {
            UserCapital userCapital = userCapitalService.getByUserIdAndCoinTypeIdAndUserType(userId, coinTypeId, UserType.SHAREHOLDER);
            ShareholderLevel oldLevel = shareholderLevelService.getByShareholderId(userId);
            oldLevel.setLevel(shareholderLevel);
            if (userCapital == null) {
                UserCapital newCapital = new UserCapital();
                newCapital.setUserId(userId);
                newCapital.setCoinTypeId(coinTypeId);
                newCapital.setAliveCoinCount(aliveCoinCount);
                newCapital.setSleepCoinCount(sleepCoinCount);
                newCapital.setType(UserType.SHAREHOLDER);
                userCapitalService.insert(newCapital);
            } else {
                if (sleepCoinCount.compareTo(userCapital.getSleepCoinCount()) != 0 && shareholderLevel.equals(oldLevel.getLevel())) {
                    int i = shareholderLevelListServive.calcaulateShareholderLevel(userId);
                    oldLevel.setLevel(i);
                    shareholderLevelListServive.calculateShareholderLevelCount();
                }
                userCapital.setAliveCoinCount(aliveCoinCount);
                userCapital.setSleepCoinCount(sleepCoinCount);
                userCapitalService.update(userCapital);
            }

            shareholderLevelService.update(oldLevel);

            if (password != null) {
                User user = userService.getByPrimaryKey(userId);
                user.setPassword(MD5Util.md5(password));
                userService.update(user);
            }
            baseDto.setData("修改成功");
        } catch (Exception e) {
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("修改失败");
        }
        return baseDto;
    }

    @RequestMapping("/memberLevel/list")
    public BaseDto getMemberLevelList() {
        List<MemberLevel> all = memberLevelService.getAll();
        return BaseDto.ok(all);
    }

    @RequestMapping("/shareholderLevel/list")
    public BaseDto getShareholderList() {
        List<ShareholderLevelList> all = shareholderLevelListServive.getAllLevel();
        return BaseDto.ok(all);
    }

    @RequestMapping("/memberLevel/update")
    public BaseDto getMemberLevelUpdate(Integer levelId,
                                        BigDecimal low,
                                        BigDecimal high) {
        MemberLevel memberLevel = memberLevelService.getByPrimaryKey(levelId);
        BigDecimal oldLow = memberLevel.getLow();
        BigDecimal oldHigh = memberLevel.getHigh();
        if (memberLevel.getCount() != 0) {
            return BaseDto.error("该等级下有会员,不可修改");
        }

        MemberLevel nextLevel = new MemberLevel();
        MemberLevel lastLevel = new MemberLevel();

        if (oldLow.compareTo(low) != 0) {
            memberLevel.setLow(low);
            //判断是否是第一个等级,如果不是第一个等级需要修改上一个等级的最大值
            if (levelId != 1) {
                lastLevel = memberLevelService.getByPrimaryKey(levelId - 1);
                lastLevel.setHigh(low);
                memberLevelService.update(lastLevel);
            }
        }

        if (oldHigh.compareTo(high) != 0) {
            memberLevel.setHigh(high);
            //判断是否是最后一个等级,如果不是最后一个等级需要修改下一个等级的最小值
            if (levelId != 10) {
                nextLevel = memberLevelService.getByPrimaryKey(levelId + 1);
                nextLevel.setLow(high);
                memberLevelService.update(nextLevel);
            }
        }

        memberLevelService.update(memberLevel);
        return BaseDto.ok("修改成功");
    }

    @RequestMapping("/shareholderLevel/update")
    public BaseDto getShareholderUpdate(Integer levelId,
                                        BigDecimal low,
                                        BigDecimal high) {
        ShareholderLevelList shareholderLevelList = shareholderLevelListServive.getByPrimaryKey(levelId);
        BigDecimal oldLow = shareholderLevelList.getLow();
        BigDecimal oldHigh = shareholderLevelList.getHigh();
        if (shareholderLevelList.getCount() != 0) {
            return BaseDto.error("该等级下有会员,不可修改");
        }

        ShareholderLevelList nextLevel = new ShareholderLevelList();
        ShareholderLevelList lastLevel = new ShareholderLevelList();

        if (oldLow.compareTo(low) != 0) {
            shareholderLevelList.setLow(low);
            //判断是否是第一个等级,如果不是第一个等级需要修改上一个等级的最大值
            if (levelId != 1) {
                lastLevel = shareholderLevelListServive.getByPrimaryKey(levelId - 1);
                lastLevel.setHigh(low);
                shareholderLevelListServive.update(lastLevel);
            }
        }

        if (oldHigh.compareTo(high) != 0) {
            shareholderLevelList.setHigh(high);
            //判断是否是最后一个等级,如果不是最后一个等级需要修改下一个等级的最小值
            if (levelId != 10) {
                nextLevel = shareholderLevelListServive.getByPrimaryKey(levelId + 1);
                nextLevel.setLow(high);
                shareholderLevelListServive.update(nextLevel);
            }
        }

        shareholderLevelListServive.update(shareholderLevelList);
        return BaseDto.ok("修改成功");
    }

    /**
     * 待解冻列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/admin/unfrozenList")
    public BaseDto getUnFrozenList(@RequestParam(defaultValue = "1", value = "pageNum") int pageNum,
                                   @RequestParam(defaultValue = "15", value = "pageSize") int pageSize){
        List<UserUnfrozenList> userUnFrozenList = userRoleService.getUserUnFrozenList(pageNum,pageSize);
        return BaseDto.ok(userUnFrozenList);
    }

    /**
     * 解冻
     * @param userId
     */
    @RequestMapping("/admin/unfrozen")
    public BaseDto adminUnFrozen(Integer userId, Integer userType) {
        BaseDto baseDto = userWalletFrozeService.unFrozenUser(userId, userType);
        return baseDto;
    }
}
